package com.contactbook.web.server.dto;

import java.util.HashSet;
import java.util.Set;

import com.contactbook.web.client.dto.AccountDTO;
import com.contactbook.web.client.dto.ContactDTO;
import com.contactbook.web.client.dto.GroupDTO;

import contactbook.model.Account;
import contactbook.model.Contact;
import contactbook.model.Group;

public class AccountDTOConverter {
	
	public static AccountDTO convert(Account account, boolean referenced) {
		AccountDTO accountDTO = new AccountDTO(account.getLogin(), account.getPassword());
		accountDTO.setId(account.getId());
		
		if (referenced == true) {
			Set<Group> groups = account.getGroups();
			Set<GroupDTO> groupDTOs = new HashSet<GroupDTO>(groups.size());
	
			if (!groups.isEmpty()) {
				for (Group group : groups) {
					groupDTOs.add(GroupDTOConverter.convert(group, false));
				}
			}
			accountDTO.setGroups(groupDTOs);
		}
		
		if (referenced == true) {
			Set<Contact> contacts = account.getContacts();
			Set<ContactDTO> contactDTOs = new HashSet<ContactDTO>(contacts.size());
			if (!contacts.isEmpty()) {
				for (Contact contact : contacts) {
					contactDTOs.add(ContactDTOConverter.convert(contact, false));
				}
			}
			accountDTO.setContacts(contactDTOs);
		}
		
    	return accountDTO;
	}
	
	public static Account convertDTO(AccountDTO accountDTO, boolean referenced) {
		Account account = new Account(accountDTO.getLogin(), accountDTO.getPassword());
		account.setId(accountDTO.getId());
		
		if (referenced) {
			Set<GroupDTO> groupsDTO = accountDTO.getGroups();
			Set<Group> groups = new HashSet<Group>(groupsDTO.size());
			if (groupsDTO != null) {
				for (GroupDTO groupDTO : groupsDTO) {
					groups.add(GroupDTOConverter.convertDTO(groupDTO, false));
				}
			}
			account.setGroups(groups);

			Set<ContactDTO> contactsDTO = accountDTO.getContacts();
			Set<Contact> contacts = new HashSet<Contact>(contactsDTO.size());
			if (contactsDTO != null) {
				for (ContactDTO contactDTO : contactsDTO) {
					contacts.add(ContactDTOConverter.convertDTO(contactDTO, false));
				}
			}
			account.setContacts(contacts);
		}
		
    	return account;
	}

}
